package com.example.ktwentong;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.viewpager.widget.ViewPager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wentong.InfoBean;
import com.example.wentong.KTWenTongAPI;
import com.example.wentong.ReadDataListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.MOUNT_UNMOUNT_FILESYSTEMS"};
    private TextView textView;
    private ViewPager myViewPager;
    private MyPagerAdapter myPagerAdapter;
    private List<String> tupianPath = new ArrayList<String>();
    private ProgressDialog mdialog;
    private ViewGroup viewGroup;
    private ImageView[] tips;
    //    private KTWenTongAPI kTwentongAPI;
    private int current;
    private KTWenTongAPI ktWenTongAPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        verifyStoragePermissions(this);//写权限
        textView = (TextView) findViewById(R.id.tv_show_result);
        myViewPager = (ViewPager) findViewById(R.id.viewpager);
        viewGroup = (ViewGroup) findViewById(R.id.tip_group);
//        kTwentongAPI = new KTWenTongAPI(this);
        bindDate();
        ktWenTongAPI = KTWenTongAPI.getInstance(this);
//        ktWenTongAPI.setIsFirstOnCreate(true);
        ktWenTongAPI.setReadDataListener(new ReadDataListener() {
            @Override
            public void onReadData(int status, InfoBean infoBean) {
                switch (status) {
                    case 0:
                        mdialog = ProgressDialog.show(MainActivity.this, "", "核心初始化中....");
                        break;
                    case 10:
                        if (mdialog != null) {
                            mdialog.dismiss();
                            mdialog = null;
                        }
                        break;
                    case 15:
                        textView.setText(infoBean.getResult());
                        break;
                    case 20:
                        textView.setText(infoBean.getResult());
                        break;
                    case 80:
                        textView.setText(infoBean.getResult());
                        break;
                    case 100:
                        tupianPath.clear();
                        //添加数据源
                        addPathDate(infoBean.getStrImagePath());
                        addPathDate(infoBean.getStrImagePathIR());
                        addPathDate(infoBean.getStrImagePathUV());
                        addPathDate(infoBean.getStrHeadImagePath());
                        addPathDate(infoBean.getStrHeadImagePathEC());
                        addPathDate(infoBean.getStrSIDHeadPathName());
                        showImage();
                        textView.setText(infoBean.getResult());
                        break;
                    case 101:

                        break;
                    case 102:
                        tupianPath.clear();
                        //添加数据源
                        addPathDate(infoBean.getStrImagePath());
                        addPathDate(infoBean.getStrImagePathIR());
                        addPathDate(infoBean.getStrImagePathUV());
                        addPathDate(infoBean.getStrHeadImagePath());
                        addPathDate(infoBean.getStrHeadImagePathEC());
                        showImage();
                        textView.setText(infoBean.getResult());
                        break;
                    case 103:
                        tupianPath.clear();
                        //添加数据源
                        addPathDate(infoBean.getStrSIDHeadPathName());
                        showImage();
                        textView.setText(infoBean.getResult());
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        ktWenTongAPI.open(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ktWenTongAPI.close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ktWenTongAPI.close();
    }

    private long mPressedTime = 0;

    @Override
    public void onBackPressed() {
        long mNowTime = System.currentTimeMillis();//获取第一次按键时间
        if ((mNowTime - mPressedTime) > 2000) {//比较两次按键时间差
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mPressedTime = mNowTime;
        } else {//退出程序
//            KTWenTongAPI.isExitApp = true;
            ktWenTongAPI.close();
            this.finish();
            System.exit(0);
        }
    }


    /**
     * 更新数据源
     *
     * @param path
     */
    private void addPathDate(String path) {
        if (path != null && !path.equals("")) {
            File file = new File(path);
            if (file.exists()) {
                tupianPath.add(path);
            }
        }
    }


    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onPageSelected(int position) {
        current = position;

        for (int i = 0; i < tips.length; i++) {
            if (i == position) {
                tips[i].setBackgroundResource(R.mipmap.page_indicator_focused);
            } else {
                tips[i].setBackgroundResource(R.mipmap.page_indicator_unfocused);
            }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    /**
     * 绑定数据设置adapter
     */
    private void bindDate() {
        myPagerAdapter = new MyPagerAdapter(MainActivity.this, tupianPath);
        myViewPager.setAdapter(myPagerAdapter);
        myViewPager.setOnPageChangeListener(this);
        myViewPager.setCurrentItem(current);
    }

    private void showImage() {

        viewGroup.removeAllViews();
        tips = new ImageView[tupianPath.size()];
        for (int i = 0; i < tips.length; i++) {
            ImageView imageView = new ImageView(MainActivity.this);
            imageView.setLayoutParams(new RelativeLayout.LayoutParams(10, 10));
            tips[i] = imageView;
            if (i == 0) {
                tips[i].setBackgroundResource(R.mipmap.page_indicator_focused);
            } else {
                tips[i].setBackgroundResource(R.mipmap.page_indicator_unfocused);
            }

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(10,
                    10));
            layoutParams.leftMargin = 5;
            layoutParams.rightMargin = 5;
            viewGroup.addView(imageView, layoutParams);
        }
        current = 0;
        myPagerAdapter.notifyDataSetChanged();
        if (tupianPath.size() > 0) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;//这个参数设置为true才有效，
            Bitmap bmp = BitmapFactory.decodeFile(tupianPath.get(0), options);//这里的bitmap是个空
            int outHeight = options.outHeight;
            int outWidth = options.outWidth;
            FrameLayout.LayoutParams fl = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            textView.setLayoutParams(fl);
        }
    }

    public static void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //申请权限结果回调：
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 通过grantResults判断有没有获取到权限，如果没有，用下面的方法判断用户点禁止的时候有没有勾选不在提示。
        for (String permission : permissions) {
            //如果返回true表示用户点了禁止获取权限，但没有勾选不再提示。
            //返回false表示用户点了禁止获取权限，并勾选不再提示。
            //我们可以通过该方法判断是否要继续申请权限
            boolean shouldShow = ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
        }
    }

    public void startTest(View view) {
        startActivity(new Intent(this,TestActivity.class));
    }
}